"""SAAS 收货信息路由

包含收货信息相关的 API 接口。
"""

from fastapi import APIRouter, Query
from fastapi.responses import JSONResponse
import logging
from config.config_manager import is_debug_data_enabled, get_saas_config
from service.get_shipping_info_service import get_shipping_info

# 日志
logger = logging.getLogger(__name__)

# 创建路由器
router = APIRouter(prefix="/api/saasShippingInfo", tags=["SAAS 收货信息"])


@router.get("/shipping-info")
async def get_shipping_info_api(
        page_size: int = Query(10, description="每页大小"),
        page_num: int = Query(1, description="页码"),
        # begin_time: str = Query(None, description="开始时间，格式: yyyy-MM-dd HH:mm:ss"),
        # end_time: str = Query(None, description="结束时间，格式: yyyy-MM-dd HH:mm:ss"),
        # inc_num: int = Query(None, description="自增ID"),
        # ord_nos: str = Query(None, description="采购主单号数组，逗号分隔"),
        # ord_detl_codes: str = Query(None, description="采购细单号数组，逗号分隔"),
        # his_ord_nos: str = Query(None, description="HIS采购主单号数组，逗号分隔"),
        # his_unique_keys: str = Query(None, description="HIS采购细单号数组，逗号分隔"),
        # shp_nos: str = Query(None, description="发货单号数组，逗号分隔"),
        # shp_detl_nos: str = Query(None, description="发货明细单号数组，逗号分隔"),
        # shp_stas: int = Query(None, description="状态: 1-待收货; 2-拒绝收货; 3-已收货"),
        # entp_shp_nos: str = Query(None, description="企业发货单号数组，逗号分隔"),
        # entp_codes: str = Query(None, description="企业编号数组，逗号分隔"),
        # invo_code: str = Query(None, description="发票代码"),
        # invono: str = Query(None, description="发票号码"),
        # prod_names: str = Query(None, description="药品名称数组，逗号分隔"),
        # prodentp_names: str = Query(None, description="生产企业数组，逗号分隔"),
        # pubonln_prod_ids: str = Query(None, description="省药品编码数组，逗号分隔"),
        # his_drug_ids: str = Query(None, description="HIS药品编码数组，逗号分隔"),
        # stroom_id: str = Query(None, description="库房id"),
        # stroom_name: str = Query(None, description="库房名称"),
):
    """获取SaaS系统收货信息"""
    try:
        # 构建请求参数
        request_params = {
            "pageSize": page_size,
            "pageNum": page_num
        }

        # 添加可选参数
        optional_params = {
            # "beginTime": begin_time,
            # "endTime": end_time,
            # "incNum": inc_num,
            # "ordNos": ord_nos,
            # "ordDetlCodes": ord_detl_codes,
            # "hisOrdNos": his_ord_nos,
            # "hisUniqueKeys": his_unique_keys,
            # "shpNos": shp_nos,
            # "shpDetlNos": shp_detl_nos,
            # "shpStas": shp_stas,
            # "entpShpNos": entp_shp_nos,
            # "entpCodes": entp_codes,
            # "invoCode": invo_code,
            # "invono": invono,
            # "prodNames": prod_names,
            # "prodentpNames": prodentp_names,
            # "pubonlnProdIDs": pubonln_prod_ids,
            # "hisDrugIds": his_drug_ids,
            # "stroomId": stroom_id,
            # "stroomName": stroom_name
        }

        for key, value in optional_params.items():
            if value is not None:
                request_params[key] = value

        logger.info(f"开始获取SaaS平台收货信息，参数: {request_params}")

        # 调用核心函数获取收货信息
        shipping_info = get_shipping_info(request_params)

        logger.info(f"成功获取SaaS平台 {len(shipping_info)} 条收货信息")

        # 调试模式下的详细数据输出
        if is_debug_data_enabled() and shipping_info:
            logger.info(f"第一条收货信息: {shipping_info[0]}")

        return {
            "success": True,
            "data": shipping_info,
            "count": len(shipping_info),
        }

    except Exception as e:
        logger.error(f"获取SaaS平台收货信息失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e),
            }
        )


@router.get("/all-shipping-info")
async def get_all_shipping_info_api():
    """获取所有收货信息（分页获取全部数据）"""
    try:
        logger.info("开始获取SaaS平台所有收货信息")

        # 调用服务类获取所有收货信息
        from service.get_shipping_info_service import get_shipping_info_service
        all_shipping_info = get_shipping_info_service.get_all_shipping_info()

        logger.info(f"成功获取SaaS平台所有收货信息，共 {len(all_shipping_info)} 条")

        # 调试模式下的详细数据输出
        if is_debug_data_enabled() and all_shipping_info:
            logger.info(f"第一条收货信息: {all_shipping_info[0]}")

        return {
            "success": True,
            "data": all_shipping_info,
            "count": len(all_shipping_info),
        }

    except Exception as e:
        logger.error(f"获取SaaS平台所有收货信息失败: {str(e)}")
        return JSONResponse(
            status_code=500,
            content={
                "success": False,
                "error": str(e),
            }
        )


__all__ = ["router"]